package graffeo.osu;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

public class ListAdapter extends ArrayAdapter<Integer>{
	public static final int EMPTY = 0;
	public static final int ROBOT = 1;
	public static final int PLAYER = 2;

	private Context context;
	private ArrayList<Integer> cells;

	public ListAdapter(Context context, int textViewResourceId, ArrayList<Integer> cells) {
		super(context, textViewResourceId, cells);

		this.cells = cells;
		this.context = context;
	}

	@Override
	public int getCount(){
		try{
			return cells.size();
		}catch(Exception e){
			return 0;
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v;

		try{
			if(convertView == null){
				LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.cell, null);
			}else
				v = convertView;

			ImageView image = (ImageView) v.findViewById(R.id.cell);
			image.setBackgroundColor(Color.BLACK);
			
			switch(cells.get(position)){
			case EMPTY:
				image.setImageResource(R.drawable.robot);
				break;

			case PLAYER:
				image.setImageBitmap(scaleResource(R.drawable.me));
				break;

			case ROBOT:
				image.setImageBitmap(scaleResource(R.drawable.bot));
				break;
			}

			return v;
		}catch(Exception e){
			return convertView;
		}
	}

	private Bitmap scaleResource(int id){
		try {
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			o.inPurgeable = true;
			o.inInputShareable = true;

			BitmapFactory.decodeResource(context.getResources(), id);

			final int REQUIRED_SIZE = 70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			
			while(!(width_tmp/2 < REQUIRED_SIZE || height_tmp/2 < REQUIRED_SIZE)){
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			BitmapFactory.Options ops = new BitmapFactory.Options();
			ops.inSampleSize=scale;
			ops.inPurgeable = true;
			ops.inInputShareable = true;

			return BitmapFactory.decodeResource(context.getResources(), id);
		} catch (Exception e) {
			return null;
		}
	}
}